package com.py.credit.controller;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.service.HomeCreditMapService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.SSearchService;
import com.py.credit.utils.NumberUtils;
import com.py.credit.utils.elasticsearch.EsPage;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 异议处理controller
 */
@RestController
@RequestMapping(value = "/homecreditMap")
public class HomeCreditMapController {

    @Autowired
    private HomeCreditMapService creditMapService;

    @Autowired
    private RemoteBaseService remoteBaseService;
    
    @Autowired
    private SSearchService sSearchService;

    @Value("${absolutepath}")
    private String absolutepath;

    /**
     * 天地图调用字典值
     */
    private static String TDMAP = "TDMAP";
    /**
     * 天地图调用URL
     */
    private static String TDURL = "URL";
    /**
     * 天地图调用KEY
     */
    private static String TDKEY = "KEY";

    /**
     * @api {get} /creditMap/updateLonAndLat.json 经纬度更新定时任务
     * @apiName updateLonAndLat
     * @apiVersion 0.0.1
     * @apiGroup 经纬度更新
     */
    @IgnoreAuthority
    @RequestMapping(value = "/updateLonAndLatPer.do")
    public RestServiceResult<Object> updateLonAndLat() {
        try {
            String mapUrl = remoteBaseService.getDictByDtlKey(TDMAP, TDURL).getData().getDtlValue();
            String mapKey = remoteBaseService.getDictByDtlKey(TDMAP, TDKEY).getData().getDtlValue();
            creditMapService.updateLonAndLat(mapUrl, mapKey);
            creditMapService.updateLonAndLatPer(mapUrl, mapKey);
            return new RestServiceResult<>();
        } catch (Exception e) {
            RestServiceResult<Object> result = new RestServiceResult<Object>();
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("经纬度更新定时任务异常！ERROR:" + e.getMessage());
            ExceptionLogger.error("经纬度更新定时任务DataRemindController#taskRemind", "任务提醒定时任务异常！ERROR:" + e.getMessage(), e);
            return result;
        }
    }
    
    @IgnoreAuthority
    @RequestMapping(value = "/getMapData.json")
    public RestServiceResult<Object> getMapData(String type,String mainType,String deptid) {
        try {
            return new RestServiceResult<>(creditMapService.getMapData(type,mainType,deptid));
        } catch (Exception e) {
            RestServiceResult<Object> result = new RestServiceResult<Object>();
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg(e.getMessage());
            return result;
        }
    }
    
    /**
     * 查询企业列表页面
     *
     * @param page
     * @return
     */
    @RequestMapping(value = "/queryAllAreaCodes.json")
    public RestServiceResult<List<Map>> queryAllAreaCodes(HttpServletRequest request) {
        RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("DissentInfoController#getList", "未获取到当前用户信息！");
                return result;
            }

            result.setData(creditMapService.queryAllAreaCodes());
            return result;
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;

        }
    }
    
    @IgnoreAuthority
    @RequestMapping(value = "/countByType.json")
    public RestServiceResult<Object> countByType() {
        try {
            return new RestServiceResult<>(creditMapService.countByType());
        } catch (Exception e) {
            RestServiceResult<Object> result = new RestServiceResult<Object>();
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg(e.getMessage());
            return result;
        }
    }
    
    /**
     * 功能描述: 覆盖率统计定时任务
     *
     * @author YaoS
     * @date 19/4/8 18:24
     */
    @IgnoreAuthority
    @RequestMapping(value = "/insertData.do")
    public RestServiceResult<Object> insertData() {
        RestServiceResult<Object> r = new RestServiceResult<>();
        try {
        	creditMapService.insertData();
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.toString());
            ExceptionLogger.error("覆盖数据插入失败异常！", e.getMessage(), e);
        }
        return r;
    }
    
    
    @RequestMapping(value = "/selectFrCount.json")
    public RestServiceResult<Object> selectFrCount() {
        RestServiceResult<Object> r = new RestServiceResult<>();
        try {
        	r.setData(creditMapService.selectFrCount());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.toString());
        }
        return r;
    }
    
    @IgnoreAuthority
    @RequestMapping(value = "/getSubjectList.json")
    public RestServiceResult<List<Map<String, String>>> getSubjectLsit(@RequestParam(value = "kId") String kId,
                                                                       @RequestParam(value = "input") String input, Page page, EsPage esPage) {

        List<Map<String, String>> keyWords = null;

        int total = 0;

        if (StringUtils.isNotBlank(input)) {
                keyWords = creditMapService.getSubjectLsitForPage(kId, input, page);

                total = page.getTotalCount();
        }
        return new RestServiceResult<List<Map<String, String>>>(total,
                keyWords == null ? new ArrayList<Map<String, String>>() : keyWords);

    }
    
    @IgnoreAuthority
    @RequestMapping(value = "/getWarnData.json")
    public RestServiceResult<Object> getWarnData(@RequestParam(value = "id") String id,
                                                                       @RequestParam(value = "tybm") String tybm, Page page, EsPage esPage) {
    	RestServiceResult<Object> r = new RestServiceResult<Object>();
    	
    	r.setData(creditMapService.getWarnData(id, tybm));
    	
    	return r;

    }
    
    
    @RequestMapping(value = "/getHistoryList.json")
    public RestServiceResult<List<Map<String, Object>>> getHistoryList(HttpServletRequest request,
                                                                       @RequestParam(value = "kId") String kId) {

        long userId = 0L;

        RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));

        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {

            SysUser userInfo = user.getData();

            if (null != userInfo) {

                userId = userInfo.getId();

            } else {

                ExceptionLogger.error("SsearchController#getHistoryList", "未获取到当前用户信息！");
            }

        } else {

            ExceptionLogger.error("SsearchController#getHistoryList", "未获取到当前用户信息！");
        }

        List<Map<String, Object>> historyLsit = sSearchService.getSharingSearchHistoryList(userId, kId);

        List<Map<String, Object>> uniqueList = new ArrayList<Map<String, Object>>(historyLsit.size());

        for (Map<String, Object> map : historyLsit) {

            Map<String, Object> singleReocrd = sSearchService.getUniqueList(map);

//            if ("100001".equals(kId) && !CollectionUtils.isEmpty(singleReocrd)) {
//
//                String idEncrypt = NumberUtils.idEncrypt((String) singleReocrd.get("B000002"));
//                singleReocrd.put("B000002", idEncrypt);
//
//            }

            if (singleReocrd != null) {

                uniqueList.add(singleReocrd);

            }

        }

        return new RestServiceResult<List<Map<String, Object>>>(uniqueList);

    }
    
}